//
//  StreamSocketViewController.swift
//  MyDemoSwift
//
//  Created by 张鑫 on 2021/11/10.
//  Copyright © 2021 张鑫. All rights reserved.
//

import UIKit

class StreamSocketViewController: UIViewController, StreamDelegate {
    
    var inputStream:InputStream?
    var outputStream:OutputStream?
    
    let socketUrl = "192.168.2.2"//ABCD:EF01:2345:6789:ABCD:EF01:2345:6789
    let socketPort:UInt16 = 8888

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }
    
    // MARK: - stream socket
    func streamSocket() {
        
        var readStream:Unmanaged<CFReadStream>? = nil
        var writeStream:Unmanaged<CFWriteStream>? = nil
        CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, socketUrl as CFString, UInt32(socketPort), &readStream, &writeStream)
        
        print("\(type(of: readStream)) \(String(describing: readStream))")
        print("\(type(of: writeStream)) \(String(describing: writeStream))")

        inputStream = readStream?.takeUnretainedValue()
        inputStream?.delegate = self
        inputStream?.setProperty(StreamSocketSecurityLevel.ssLv2, forKey: Stream.PropertyKey.socketSecurityLevelKey)
        inputStream?.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
        inputStream?.open()
        
        outputStream = writeStream?.takeUnretainedValue()
        outputStream?.delegate = self
        outputStream?.schedule(in: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
        outputStream?.open()
    }
    
    func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
        print("\(String(describing: eventCode) )")
        switch eventCode {
        case .openCompleted:
            
            break
            
        case .hasBytesAvailable:
            if aStream == inputStream {
                var buffer:[UInt8] = [UInt8](repeating: 0, count: 100)
                inputStream?.read(&buffer, maxLength: 100)
            }
            break
            
        case .hasSpaceAvailable:
            if aStream == outputStream {
                let name:String = "xiawtwe"
                let data = [UInt8](name.utf8)
                outputStream?.write(data, maxLength: name.count)
            }
            break
            
        case .errorOccurred:
            
            break
            
        case .endEncountered:
            
            break
            
        default:
            print("\(eventCode)")
        }
    }
}
